package com.archgeek.java.udp.v2listen;

import com.archgeek.java.udp.MessageCreator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.UUID;

/**
 * 服务提供方
 * <p>
 * 1.监听自己的一个端口,持续监听,随时停止
 *
 * @author pizhihui
 * @date 2023-03-03
 */
public class UDPProviderV2 {

    public static void main(String[] args) throws IOException {

        String sn = UUID.randomUUID().toString();
        Provider provider = new Provider(sn);
        provider.start();

        // 读取到任意字符
        System.in.read();
        provider.exit();

    }


    private static class Provider extends Thread {
        private String sn;
        private boolean done = false;
        private DatagramSocket ds = null;

        public Provider(String sn) {
            this.sn = sn;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("UDPProvider Started...");

            try {
                ds = new DatagramSocket(20000);
                // 监听的 20000 端口

                while (!done) {

                    final byte[] buf = new byte[512];
                    DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

                    // 接收消息
                    System.out.println("UDPProvider waiting msg......");
                    ds.receive(receivePack);
                    System.out.println("UDPProvider received msg......receivePack=" + receivePack);


                    String ip = receivePack.getAddress().getHostAddress();
                    int port = receivePack.getPort();
                    int dataLen = receivePack.getLength();
                    String data = new String(receivePack.getData(), 0, dataLen);
                    System.out.println("UDPProvider receive from ip: " + ip + ",port:" + port + ",data:" + data);

                    // 反馈消息到指定的端口号
                    int responsePort = MessageCreator.parsePort(data);
                    if (responsePort != -1) {
                        // 构建一份回送数据
                        String responseData = MessageCreator.buildWithSn(sn);
                        byte[] responseDataByte = responseData.getBytes();
                        DatagramPacket responsePacket = new DatagramPacket(responseDataByte, responseDataByte.length,
                                receivePack.getAddress(), responsePort);
                        ds.send(responsePacket);
                    }

                }
                System.out.println("UDPProvider Finished!");
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                if (null != ds) {
                    close();
                }
            }

        }

        private void close() {
            if (null != ds) {
                ds.close();
                ds = null;
            }
        }

        void exit() {
            done = true;
            close();
        }
    }


}
